<template>
  <div class="home-container">
    <div>
      <van-nav-bar left-arrow fixed>
        <template #right>
          <van-icon name="search" color="white" size="18" @click="$router.push({path:'/search'})"/>
        </template>
        <template #left>
          <img src="../../assets/toutiao_logo.png" alt="logo" class="logo" />
          <!-- <van-icon name="search" size="18" /> -->
        </template>
      </van-nav-bar>
    </div>
    <!-- //频道导航 -->
    <van-tabs
      v-model="active"
      animated
      sticky
      offset-top="1.22667rem"
      @click="btn"
      @change="btn"
    >
      <van-tab
        v-for="obj in list"
        :title="obj.name"
        :key="obj.id"
        :name="obj.id"
      >
        <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
          <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <Article :arr="articlelist" @action="Articleaction" @detail = 'detailFn'></Article>
          </van-list>
        </van-pull-refresh>
      </van-tab>
    </van-tabs>
    <van-icon name="plus" size="14" class="moreChannels" @click="show = true"/>
    <!-- 弹出层组件 -->
    <!-- close-on-click-overlay 是否在点击遮罩层后关闭（false 不关闭） -->
    <van-popup v-model="show" :close-on-click-overlay="false" class="edit_wrap">
      <div class="popup-container">
        <!-- 弹出层的头部区域 -->
        <van-nav-bar title="频道管理">
          <template #right>
            <van-icon
              name="cross"
              size="14"
              color="white"
              @click="closepop"
            />
          </template>
        </van-nav-bar>

        <!-- 弹出层的主体区域 -->
        <div class="pop-body">
          <ChannelEdit
          :list="list"
          :allChannelsList="unChannelList"
          @btn = 'delbtn'
          @addbtn="Addbtn"
          @changeChannel="changeEditFn"
          ref="channel"
          ></ChannelEdit>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import {
  channelListAPI,
  ArticleAPI,
  articleDislikesAPI,
  articleReportsAPI,
  allChannelsAPI,
  userChannelsAPI
} from '@/api'
//
import Article from './component/Article.vue'

// 导入遮罩层组件
import ChannelEdit from './component/ChannelEdit.vue'
import { formatime } from '@/utils/date.js'
export default {
  data () {
    return {
      show: false,
      allChannelsList: [],
      active: 0,
      list: [],
      articlelist: [],
      isLoading: false,
      loading: false,
      finished: false,
      page: 1,
      channel_id: 0,
      timestamp: 0
    }
  },
  async created () {
    const [, res] = await channelListAPI()
    // console.log(res)
    this.list = res.data.data.channels
    const [, res1] = await allChannelsAPI()
    // console.log(res1)
    this.allChannelsList = res1.data.data.channels
    this.getArticle()
  },

  components: {
    Article,
    ChannelEdit
  },
  computed: {
    unChannelList () {
      return this.allChannelsList.filter(item => {
        const index = this.list.findIndex(obj => {
          return Number(item.id) === Number(obj.id)
        })
        if (index === -1) {
          return true
        } else {
          return false
        }
      })
    }
  },
  methods: {
    formatime: formatime,
    async getArticle () {
      const [, res] = await ArticleAPI({
        channel_id: this.channel_id,
        page: this.page
      })
      //   console.log(res)
      // 把时间预处理，改为什么之前
      res.data.data.results.forEach((obj) => {
        obj.pubdate = this.formatime(obj.pubdate)
      })
      if (res.data.data.results.length === 0) {
        this.finished = true
      } else {
        this.articlelist = [...this.articlelist, ...res.data.data.results]
        this.isLoading = false
        this.loading = false
        this.timestamp = res.data.pre_timestamp
      }
    },
    // 下拉加载
    onRefresh () {
      this.page = 1
      this.articlelist = []
      this.getArticle()
    },
    // s上拉加载
    onLoad () {
      this.page++

      this.getArticle()
    },
    btn (channel_id) {
      console.log(channel_id)
      this.channel_id = channel_id
      this.page = 1
      this.articlelist = []
      this.getArticle()
    },

    asyncArtic (err) {
      // 反馈处理结果
      if (err) {
      } else {
        this.page = 1
        this.articlelist = []
        this.getArticle()
      }
    },
    async Articleaction (actionobj, art_id) {
      if (actionobj.name === '拉黑作者') {
        return
      }
      if (actionobj.name === '不感兴趣') {
        const [err] = await articleDislikesAPI({
          target: art_id
        })
        this.asyncArtic(err)
        return
      }
      {
        const [err] = await articleReportsAPI({
          target: art_id,
          type: actionobj.value
        })
        this.asyncArtic(err)
      }
    },
    async delbtn (item, index) {
      this.list.splice(index, 1)
      // 更新

      const resultList = this.list.filter(obj => {
        return obj.id !== 0
      }).map((item, index) => {
        const newobj = { ...item }
        newobj.seq = index + 1
        delete newobj.name
        return newobj
      })
      console.log(resultList)
      await userChannelsAPI({
        channels: resultList
      })
    },
    async Addbtn (item) {
      this.list.push(item)
      const arr = this.list.filter((obj) => { return obj.id !== 0 }) // 先过滤掉id为0的推荐频道, 把剩余的数组返回
      console.log(arr)

      const resultList = arr.map((item, index) => {
        const newObj = { ...item } // 浅拷贝(让对象和原数组脱离关系)
        newObj.seq = index + 1
        delete newObj.name // 删除对象里name键值对
        return newObj
      })
      // map会收集每次遍历return的值形成一个新数组
      console.log(resultList)
      await userChannelsAPI({
        channels: resultList
      })
    },
    async closepop () {
      this.$refs.channel.isEdit = false
      this.show = false
    },
    changeEditFn (channelId) {
      this.show = false
      this.active = channelId
      this.channel_id = channelId
      this.page = 1
      this.articlelist = []
    },
    detailFn (item) {
      this.$router.push({
        path: `/art_detail?art_id=${item.art_id}`
      })
    }
  }
}
</script>

<style lang="less" scoped>
.home-container {
  padding-top: 46px;
  padding-bottom: 50px;
}
.logo {
  height: 80%;
}
/deep/ .van-tabs__wrap {
  padding-right: 30px;
  background-color: #fff;
}

// 设置小图标的样式
.moreChannels {
  position: fixed;
  top: 60px;
  right: 8px;
  z-index: 999;
}

// 弹出层容器宽度高度铺满屏幕
/*频道编辑弹出层 */
.edit_wrap {
  width: 100%;
  height: 100%;
}
</style>
